package com.hrpmar.service.impl;

import com.hrpmar.controller.dto.*;
import com.hrpmar.controller.vo.Message;
import com.hrpmar.mapper.*;
import com.hrpmar.pojo.*;
import com.hrpmar.service.DruginfoService;
import com.hrpmar.utils.Constants;
import com.hrpmar.utils.Pager;
import com.hrpmar.utils.genNumUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by c on 2017-11-15.
 */
@Service
@Transactional
public class DruginfoServiceImpl implements  DruginfoService {

    @Resource
    private DruginfoMapper druginfoMapper;

    @Resource
    private DrugstockMapper drugstockMapper;

    @Resource
    private PurdetailsMapper purdetailsMapper;

    @Resource
    private DsdetailsMapper dsdetailsMapper;

    @Resource
    private OsdetailsMapper osdetailsMapper;

    @Resource
    private InvdetailsMapper invdetailsMapper;

    @Resource
    private DrugtypeMapper drugtypeMapper;

    @Resource
    private ProviderMapper providerMapper;

    @Resource
    private PurplanMapper purplanMapper;

    @Resource
    private DrugstorageMapper drugstorageMapper;

    @Resource
    private OutstorageMapper outstorageMapper;

    @Resource
    private MedicperMapper medicperMapper;


    @Override
    public Pager searchDruginfo(Integer offset, Integer limit, DruginfoDto condition) {
        Pager pager = new Pager();
        pager.setRows(druginfoMapper.searchDrugByCondition(offset,limit,condition));
        pager.setTotal(druginfoMapper.getTotal(condition));
        return pager;
    }

    /**
     * 批量删除
     * @param drugNum
     */
    @Override
    public Message batchDrugByNum(String[] drugNum) {
        StringBuffer stoSbf = new StringBuffer();
        StringBuffer infoSbf = new StringBuffer();
        Message msg = new Message();
        boolean flag = true;
        //标志库存中是否存在药品信息
        boolean drugFlag=false;
        if(drugNum!=null && drugNum.length>0){
            for(int i=0; i<drugNum.length; i++){
                //获取药品的药品名
                String drugName = druginfoMapper.getDrugByNum(drugNum[i]).getDrugName();
                //判断该药品和库存信息是否有关联
                if(drugstockMapper.existsDrug(drugNum[i])>0){
                    flag=false;
                    drugFlag=true;
                    stoSbf.append(drugName+",");
                }
                if(drugFlag==false){
                    if(purdetailsMapper.existsPurdetal(drugNum[i])>0||dsdetailsMapper.existsDsdetail(drugNum[i])>0||osdetailsMapper.existsOsdetail(drugNum[i])>0||invdetailsMapper.existsInvdertail(drugNum[i])>0){
                        flag=false;
                        infoSbf.append(drugName+"在");
                    }
                    //判断该药品信息在采购信息，入库信息，出库信息，盘点信息中有没有记录
                    if(purdetailsMapper.existsPurdetal(drugNum[i])>0){
                        infoSbf.append("采购信息,");
                    }
                    if(dsdetailsMapper.existsDsdetail(drugNum[i])>0){
                        infoSbf.append("入库信息,");
                    }
                    if(osdetailsMapper.existsOsdetail(drugNum[i])>0){
                        infoSbf.append("出库信息,");
                    }
                    if(invdetailsMapper.existsInvdertail(drugNum[i])>0){
                        infoSbf.append("盘点信息,");
                    }
                }
            }
            if(stoSbf.toString()!=null&&!stoSbf.toString().equals("")){
                stoSbf.deleteCharAt(stoSbf.length() - 1);
                msg.setStockError(stoSbf.toString()+"在库存中存有数据,您不能删除!");
            }
            if(infoSbf.toString()!=null && !infoSbf.toString().equals("")){
                infoSbf.deleteCharAt(infoSbf.length() - 1);
                msg.setInfoError(infoSbf.toString()+"中存有记录,是否要一并删除？");
            }
            if(flag==true){
                //批量删除药品信息
                if(druginfoMapper.batchDel(drugNum)>0){
                    msg.setDelSuccess("删除药品信息成功!");
                } else {
                    msg.setDelSuccess("系统繁忙,删除失败!");
                }

            }
        }
        return msg;
    }

    @Override
    public Message batchAllDrugInfoByNum(String[] drugNum) {
        Message msg = new Message();
        if(drugNum!=null && drugNum.length>0){
            for(int i=0; i<drugNum.length; i++){
                //判断药品在其他表中是否有关联,有则删除
                if(purdetailsMapper.existsPurdetal(drugNum[i])>0){
                    purdetailsMapper.delPurdetailsByDrugNum(drugNum[i]);
                }
                if(dsdetailsMapper.existsDsdetail(drugNum[i])>0){
                    dsdetailsMapper.delDsdertailsByDrugNum(drugNum[i]);
                }
                if(osdetailsMapper.existsOsdetail(drugNum[i])>0){
                    osdetailsMapper.delOsdetailsByDrugNum(drugNum[i]);
                }
                if(invdetailsMapper.existsInvdertail(drugNum[i])>0){
                    invdetailsMapper.delInvderByDrugNum(drugNum[i]);
                }
            }
            //删除该药品信息
            if(druginfoMapper.batchDel(drugNum)>0){
                msg.setDelSuccess("删除药品信息成功!");
            } else {
                msg.setDelSuccess("系统繁忙,删除失败!");
            }
        }
        return msg;
    }

    @Override
    public List<Drugtype> getDrugType() {
        return drugtypeMapper.getDrugType();
    }

    @Override
    public void addDrugInfo(Druginfo druginfo) {
        //获取药品表的最后一个编号
        String drugNum = genNumUtil.getNum(druginfoMapper.getLastDrugNum());
        System.out.println(drugNum);
        druginfo.setDrugNum(drugNum);
        druginfoMapper.addDrugInfo(druginfo);
    }

    @Override
    public void updateDtugIngo(Druginfo druginfo) {
        druginfoMapper.updateDrugInfo(druginfo);
    }

    @Override
    public Provider getPro(String ProNum) {
        return providerMapper.getProviderByNum(ProNum);
    }

    @Override
    public Pager search(Integer offset, Integer limit, PurplanDto condition) {
        Pager pager = new Pager();
        pager.setRows(purplanMapper.searchPurPlanByCondition(offset,limit,condition));
        pager.setTotal(purplanMapper.getTotal(condition));
        return pager;
    }

    @Override
    public List<Purdetails> searchDetails(String planNum) {
        return purdetailsMapper.searchDetails(planNum);
    }

    @Override
    public void addDsdels(String planNum, HttpServletRequest req) {
        HttpSession sessions = req.getSession();
        Map<String,dsdDto> map=new HashMap<String,dsdDto>();
        if(sessions.getAttribute("dsdDelsMap")!=null){
            sessions.removeAttribute("dsdDelsMap");
        }
        sessions.setAttribute("dsdDelsMap",map);
        //根据采购编号获取采购明细信息
        List<Purdetails> list = purdetailsMapper.searchDetails(planNum);
        //循环添加map
        for(Purdetails p:list){
            dsdDto d = new dsdDto();
            d.setDsdId(p.getDelId());
            d.setDrugNum(p.getDrugNum());
            d.setDsdBuyprice(p.getDelBuyprice());
            d.setDsdRetailprice(p.getDelRetailprice());
            d.setDsdOneprice(p.getDelOneprice());
            d.setDsdBuynum(p.getDelBuynum());

            map.put(p.getDrugNum(),d);
        }
    }

    @Override
    public String getNewDeNum() {
        String newNum =genNumUtil.getNum(drugstorageMapper.getOldDsNum());
        return newNum;
    }

    @Override
    public void addRukuInfo(String proNum, String planNum, String dsNum, String planDate, String dsVerifier, HttpServletRequest req) {
        SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd");
        HttpSession session = req.getSession();
        //获取session里当前登录人的信息
        Worker worker = (Worker) session.getAttribute(Constants.LOGIN_USER);
        //添加入库主表信息
        Drugstorage sto = new Drugstorage();
        sto.setDsNum(dsNum);
        sto.setPlanNum(planNum);
        try {
            sto.setPlanDate(smt.parse(planDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        sto.setProNum(proNum);
        sto.setDsVerifier(worker.getWoJubnum());
        //如果主表信息添加成功后则添加入库明细信息
        if(drugstorageMapper.addDrugstorage(sto)>0){
            //获取Session里的入库明细信息
            Map<String,dsdDto> map = (Map<String,dsdDto>) session.getAttribute("dsdDelsMap");
            Set<String> keySet = map.keySet();
            //循环添加入库明细信息
            for(String key:keySet){
                //获取单个明细信息
                dsdDto dsd = map.get(key);
                Dsdetails dsdetails = new Dsdetails();
                dsdetails.setDsNum(dsNum);
                dsdetails.setDsdValiddate(dsd.getDsdValiddate());
                dsdetails.setDrugNum(dsd.getDrugNum());
                dsdetails.setDsdBuyprice(dsd.getDsdBuyprice());
                dsdetails.setDsdRetailprice(dsd.getDsdRetailprice());
                dsdetails.setDsdOneprice(dsd.getDsdOneprice());
                dsdetails.setDsdBuynum(dsd.getDsdBuynum());
                dsdetails.setDsdLotnum(dsd.getDsdLotnum());
                //入库明细添加数据库
                dsdetailsMapper.addDsdDels(dsdetails);

                //添加库存信息
                Drugstock drugstock = new Drugstock();
                drugstock.setStoNum(genNumUtil.getNum(drugstockMapper.getLastStoNum()));
                drugstock.setDrugNum(dsd.getDrugNum());
                drugstock.setStoPcs(dsd.getDsdBuynum());
                drugstock.setStoPutindate(new Date());
                drugstock.setStoLotnum(dsd.getDsdLotnum());
                drugstock.setProNum(proNum);
                drugstock.setStoMfg(dsd.getStoMfg());
                drugstock.setStoValiddate(dsd.getDsdValiddate());
                drugstock.setStoPrimecost(dsd.getDsdBuyprice());
                drugstock.setStoPresell(dsd.getDsdOneprice());
                //添加
                drugstockMapper.addDrugStock(drugstock);
            }
            //修改采购单入库状态(已入库)
            purplanMapper.upRuState(1,planNum);
        }
    }

    @Override
    public Pager searchRu(Integer offset, Integer limit, DrugstorageDto condition) {
        Pager pager = new Pager();
        pager.setRows(drugstorageMapper.search(offset,limit,condition));
        pager.setTotal(drugstorageMapper.getTotal(condition));
        return pager;
    }

    @Override
    public Drugstorage getStoByNum(String dsNum) {
        return drugstorageMapper.searStorByNum(dsNum);
    }

    @Override
    public List<Dsdetails> getdelsByNum(String dsNum) {
        return dsdetailsMapper.searchDelsByNum(dsNum);
    }

    @Override
    public Pager searchChu(Integer offset, Integer limit, OutstorageDto condition) {
        Pager pager = new Pager();
        pager.setRows(outstorageMapper.search(offset,limit,condition));
        pager.setTotal(outstorageMapper.getTotal(condition));
        return pager;
    }

    @Override
    public Outstorage searchOutstorage(String osNum) {
        return outstorageMapper.searOutstorageByNum(osNum);
    }

    @Override
    public List<Osdetails> searchOsdetails(String osNum) {
        return osdetailsMapper.searchOsdetailsByNum(osNum);
    }

    @Override
    public List<Medicper> getAllMed() {
        return medicperMapper.getAllMedicper();
    }

    @Override
    public Medicper getMedById(Integer perId) {
        return medicperMapper.getMedById(perId);
    }

    @Override
    public String getNewOutNum() {
        return genNumUtil.getNum(outstorageMapper.getLastOutNum());
    }

    @Override
    public List<Drugstock> searchStoByDrugNum(String drugNum) {
        return drugstockMapper.searchStockByDrugNum(drugNum);
    }

    @Override
    public Drugstock getStoBystoLotnum(String stoLotnum,String drugNum) {
        return drugstockMapper.getStoBystoLotnum(stoLotnum,drugNum);
    }

    @Override
    public Map<Integer,OsdetailsDto> setOutDelsInMap(OsdetailsDto osd,HttpServletRequest req) {
        HttpSession sessions = req.getSession();
        Map<Integer,OsdetailsDto> map=null;
        if(sessions.getAttribute("osdetailsMap")==null){
            map = new HashMap<Integer,OsdetailsDto>();
            sessions.setAttribute("osdetailsMap",map);
        }
        map = (Map<Integer,OsdetailsDto>) sessions.getAttribute("osdetailsMap");

        Integer newId = map.size()+1;
        osd.setKeyId(newId);
        map.put(newId,osd);
        return map;
    }

    @Override
    public void delOutDels(Integer keyId, HttpServletRequest req) {
        HttpSession sessions = req.getSession();
        Map<Integer,OsdetailsDto> map = (Map<Integer,OsdetailsDto>) sessions.getAttribute("osdetailsMap");
        map.remove(keyId);
    }

    @Override
    public void updateOutDels(Integer osdNum, Integer keyId, HttpServletRequest req) {
        HttpSession sessions = req.getSession();
        Map<Integer,OsdetailsDto> map = (Map<Integer,OsdetailsDto>) sessions.getAttribute("osdetailsMap");
        map.get(keyId).setOsdNum(osdNum);
    }

    @Override
    public void addOutstoAndDsdeltails(Outstorage outstorage, HttpServletRequest req) {
        HttpSession session = req.getSession();
        //添加出库主表信息
        if(outstorageMapper.addOutsto(outstorage)>0){
            //添加出库明细信息
            Map<Integer,OsdetailsDto> map = (Map<Integer,OsdetailsDto>) session.getAttribute("osdetailsMap");
            Set<Integer> keySet = map.keySet();
            for(Integer key:keySet){
                OsdetailsDto od = map.get(key);
                Osdetails osdetails = new Osdetails();
                osdetails.setOsNum(od.getOsNum());
                osdetails.setOsdValiddate(od.getOsdValiddate());
                osdetails.setDrugNum(od.getDrugNum());
                osdetails.setOsdLotnum(od.getOsdLotnum());
                osdetails.setOsdOneprice(od.getOsdOneprice());
                osdetails.setOsdNum(od.getOsdNum());
                //添加明细信息
                if(osdetailsMapper.addDsdetails(osdetails)>0){
                    //修改库存信息
                    drugstockMapper.delDrugStoByDrug(osdetails.getOsdNum(),osdetails.getDrugNum(),osdetails.getOsdLotnum());
                }
            }
            session.removeAttribute("osdetailsMap");
        }
    }
}
